package com.example.designpattern.responsibility_three;

import com.example.model.GoodsDTO;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Comparator;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author long
 * @date 2025/6/16 17:42
 */
@Service
public class ValidatorChainService implements IValidatorChain, InitializingBean {

    @Autowired
    private List<IValidator> validatorList;

    private final ThreadLocal<AtomicInteger> threadLocal = ThreadLocal.withInitial(AtomicInteger::new);

    @Override
    public void validate(GoodsDTO dto) {
        int index = threadLocal.get().getAndIncrement();
        // 责任链校验完成，退出
        if(index >= validatorList.size()){
            threadLocal.remove();
            return;
        }

        // 获取责任链节点，触发校验
        try{
            validatorList.get(index).validate(dto,this);
        }catch (Exception e){
            threadLocal.remove();
            throw e;
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        validatorList.sort(Comparator.comparing(IValidator::getPriority));
    }

}
